package com.study.hot.architecture.mvx.mvc.controller;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.study.hot.R;
import com.study.hot.architecture.mvx.mvp.model.Board;
import com.study.hot.architecture.mvx.mvp.model.Player;


/**
 * <pre>
 *     author : slx
 *     time   : 2020/11/20
 *     desc   : 井字棋改为mvc架构
 * </pre>
 */
public class MvcJZQActivity extends AppCompatActivity {

    // 属于View的
    private GridLayout gridLayout;
    private TextView tvWinner;
    private Board model;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jingziqi);
        gridLayout = findViewById(R.id.buttonViewGroup);
        tvWinner = findViewById(R.id.winnerTv);
        model = new Board();
    }

    // 刷新UI
    public void refreshUI() {
        tvWinner.setText("");
        int childCount = gridLayout.getChildCount();
        for (int i = 0; i < childCount; i++) {
            ((Button) gridLayout.getChildAt(i)).setText("");
        }
    }

    /**
     * item 点击下棋
     *
     * @param view
     */
    public void onCellClicked(View view) {
        Button button = (Button) view;
        // 从tag属性中计算当前点击的行、列
        String btnTag = button.getTag().toString();

        int row = Integer.parseInt(btnTag.substring(0, 1));
        int col = Integer.parseInt(btnTag.substring(1, 2));

        Player playerThatMoved = model.mark(row, col);
        if (playerThatMoved != null) {
            button.setText(playerThatMoved.toString());
            if (model.getWinner() != null) {
                tvWinner.setText(String.format("%s 获胜", playerThatMoved.toString()));
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu_jingziqi, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_reset:
                model.restart();
                refreshUI();
                return true;
            default:
                return super.onOptionsItemSelected(item);

        }
    }
}
